package com.weige.elefence.mq;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 演示TTL+DLX完成延时队列
 * @author ltj
 */
public class QueueTest3 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //连接IP
        connectionFactory.setHost("192.168.1.108");
        //连接端口
        connectionFactory.setPort(5672);
        //虚拟主机(默认为/)
        connectionFactory.setVirtualHost("/");
        //账号 默认是guest
        connectionFactory.setUsername("root");
        //密码 默认是guest
        connectionFactory.setPassword("123456");
        //创建连接
        Connection connection = connectionFactory.newConnection();
        //创建信道
        Channel channel = connection.createChannel();

        //创建死信交换器 与队列等
        channel.exchangeDeclare("DEAD_LETTER_EXCHANGE", BuiltinExchangeType.DIRECT, false, false, false, null);
        channel.queueDeclare("DEAD_LETTER_QUEUE", false, false, false, null);
        channel.queueBind("DEAD_LETTER_QUEUE", "DEAD_LETTER_EXCHANGE", "DL");

        //创建交换器队列等并绑定死信交换器并指定队列中的消息的过期时间为5秒
        channel.exchangeDeclare("shanguoyu", BuiltinExchangeType.DIRECT, false, false, false, null);
        Map<String, Object> map = new HashMap<>(16);
        map.put("x-message-ttl", TimeUnit.SECONDS.toMillis(20));
        map.put("x-dead-letter-exchange", "DEAD_LETTER_EXCHANGE");
        map.put("x-dead-letter-routing-key", "DL");
        channel.queueDeclare("shanguoyu", false, false, false, map);
        channel.queueBind("shanguoyu", "shanguoyu", "shanguoyu");
    }
}